package com.neusoft.databus.agent.pool.netty;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.databus.common.connection.AbstractConnection;
import com.neusoft.databus.common.connection.SocketConnection;
import com.neusoft.databus.common.pool.Connector;

import lombok.extern.slf4j.Slf4j;

/**
 * description
 *
 * @author sunchf
 * @date 2018年12月13日 下午3:10:17
 */
@Slf4j
@Component
public class NettyConnector implements Connector<NettyWrapper> {

    @Autowired
    NettyPool pool;

    @Override
    public NettyWrapper getConn(AbstractConnection connection) throws Exception {
        final NettyWrapper client = this.pool.borrowObject((SocketConnection) connection);
        return client;
    }

    @Override
    public NettyWrapper getConn(AbstractConnection connection, int timeout) throws Exception {
        final NettyWrapper client = this.pool.borrowObject((SocketConnection) connection, timeout * 1000);
        return client;
    }

    @Override
    public void returnConn(AbstractConnection connection, NettyWrapper client) {
        this.pool.returnObject((SocketConnection) connection, client);
    }

    @Override
    public void invalidateConn(AbstractConnection connection, NettyWrapper client) {
        if (null == client) {
            return;
        }
        try {
            this.pool.invalidateObject((SocketConnection) connection, client);
            NettyConnector.log.info("invalidate pooled netty client {}", connection.toString());
        } catch (final Exception e) {
            NettyConnector.log.error(e.getMessage(), e);
        }
    }

    @Override
    public void removeAllConns(AbstractConnection connection) {
        try {
            this.pool.clear((SocketConnection) connection);
            NettyConnector.log.info("clear pooled netty client {}", connection.toString());
        } catch (final Exception e) {
            NettyConnector.log.error(e.getMessage(), e);
        }

    }

}
